<template>
	<div>
		<el-dialog :title="title" :visible.sync="dialogVisible" width="85%" @close="handleClose">
			<el-form :model="form" :rules="rules" ref="form" label-width="150px"
				class="demo-ruleForm" v-loading="loading">
				<el-tabs v-model="activeName" type="card">
					<!-- <el-tab-pane label="基本信息" name="1"> -->
						<el-row :gutter="20">
							<el-col :span="12">
								<el-form-item label="征集标题" prop="headline">
									<el-input type="text" v-model="form.headline" placeholder="请输入征集标题" maxlength="100"
										show-word-limit></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="适用行业" prop="applicableTargets">
									<el-select v-model="form.applicableTargets" filterable placeholder="请选择">
										<el-option v-for="item in applicableTargetsOptions" :key="item.id"
											:label="item.label" :value="item.value">
										</el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="有效期起止" prop="timeArr">
									<el-date-picker type="daterange" placeholder="选择日期" v-model="form.timeArr"
										value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 420px;height: 39px;"></el-date-picker>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="关键字" prop="keywordes">
									<el-input type="text" v-model="form.keywordes" maxlength="20" placeholder="请输入关键字"
										show-word-limit>
									</el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="联系人" prop="contactRen">
									<el-input type="text" v-model="form.contactRen" maxlength="20" placeholder="请输入联系人"
										show-word-limit>
									</el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="联系电话" prop="contactPhone">
									<el-input type="text" v-model="form.contactPhone" maxlength="11" placeholder="请输入联系电话"
										show-word-limit>
									</el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="征集描述" prop="settleMatter">
									<el-input type="textarea" v-model="form.settleMatter" maxlength="200" placeholder="请输入征集描述"
										show-word-limit :rows="5">
									</el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="征集要求" prop="expectedEffect">
									<el-input type="textarea" v-model="form.expectedEffect" placeholder="请输入征集要求" maxlength="200" 
										show-word-limit :rows="5">
									</el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="附件">
									<el-upload :action="imageUploadUrl" name="file" :on-success="handleAvatarSuccess6"
										:on-error="handleError6" :on-remove="handleRemove6" :file-list="fileAll">
										<el-button size="small" type="primary" plain>点击上传</el-button>
										<div slot="tip" class="el-upload__tip">
											上传文件大小不超过10M
										</div>
									</el-upload>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item class="newIpt" ref="headimgUpload1" label="封面图片" prop="ntThumb">
									<p class="uploadTip">上传图片不超过10M，且只能上传jpg、png类型</p>
									<el-upload class="avatar-uploader" :action="imageUploadUrl" :show-file-list="false"
										:on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
										:on-error="handleError">
										<img v-if="imgUrl" :src="imgUrl" class="avatar">
										<i v-else class="el-icon-plus avatar-uploader-icon"></i>
									</el-upload>
								</el-form-item>
							</el-col>
						</el-row>
					<!-- </el-tab-pane> -->
					<!-- <el-tab-pane label="内容" name="2">
						<el-form-item label="内容" prop="mainBody">
							<div style="border: 1px solid #ccc;width:98%;line-height:21px;">
								<Toolbar style="border-bottom: 1px solid #ccc" :editor="editor"
									:defaultConfig="toolbarConfig" :mode="mode" />
								<Editor v-if="dialogVisible" style="height: 400px; overflow-y: hidden;"
									v-model="form.mainBody" :defaultConfig="editorConfig" :mode="mode"
									@onCreated="onCreated" />
							</div>
						</el-form-item>
					</el-tab-pane> -->
				</el-tabs>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="submitForm(4)">保存为草稿</el-button>
				<el-button type="primary" @click="submitForm(0)">提 交</el-button>
			</span>
		</el-dialog>
	</div>
</template>
<script>
	import {
		getNewOptions,
		getNewDetail
	} from "@/request/api/new"
	import {
		Editor,
		Toolbar
	} from '@wangeditor/editor-for-vue'
	import {
		getUploadImg
	} from "@/request/api/link"
	import {
		planCollectAdd,
		planCollectListDetail,
		getKey
	} from "@/request/api/planPromotion";
import rulesUtil from "@/utils/rules" //引入
	export default {
		components: {
			Editor,
			Toolbar
		},
		data() {
			return {
				isWrite: false,
				checked: false,
				dialogVisible: false,
				type: "",
				title: "",
				activeName: '1',
				form: {
					"headline": "", //征集标题
					"applicableTargets": "", //适用行业：方案适用的行业、机构或领域。
					"target": "", //目标用户：方案适用的用户群体。
					"settleMatter": "", //需求描述
					"expectedEffect": "", //预期效果：预期能够达到的效果。征集要求
					"collectionTimeStart": "", //投稿时间 起
					"collectionTimeEnd": "", //投稿时间 止
					timeArr:[],
					"cover": "", //封面图
					"contactPhone": "", //联系电话
					"contactRen": "", //联系人
					"keywordes": "", //关键词
					"accessoryDtos": [ //附件
						// {
						//     "correlationId": "", //关联id
						//     "accessoryName": "", //名称
						//     "accessoryUrl": "", //url
						// }
					]
				},
				imgUrl: '',
				rules: {
					headline: [{
						required: true,
						message: '请输入征集标题',
						trigger: 'blur'
					}, ],
					applicableTargets: [{
						required: true,
						message: '请选择适用行业',
						trigger: 'blur'
					}, ],
					keywordes: [{
						required: true,
						message: '请输入关键字',
						trigger: 'blur'
					}, ],
					settleMatter: [{
						required: true,
						message: '请输入征集描述',
						trigger: 'blur'
					}, ],
					expectedEffect: [{
						required: true,
						message: '请输入征集要求',
						trigger: 'blur'
					}, ],
					timeArr: [{
						required: true,
						message: '请选择起止日期',
						trigger: 'blur'
					}, ],
					contactRen: [{
						required: true,
						message: '请输入联系人',
						trigger: 'blur'
					}, ],
					contactPhone: [{
						required: true,
						validator: rulesUtil.FormValidate.Form().checkTel,
						trigger: 'blur'
					}, ],
				},
				
				selectCate: {
					checkStrictly: true,
					label: "name",
					children: "childs",
					value: "name",
					getCheckedNodes: true,
					expandTrigger: "hover",
				},
				dataTree: [],
				fileAll: [],
				imageUploadUrl: '/dev-api/file/upload/uploadNotQR',
				editor: null,
				toolbarConfig: { //工具栏配置
					excludeKeys: [
						'insertTable', //插入表格
					]
				},
				editorConfig: {
					placeholder: '请输入内容...',
					// 所有的菜单配置，都要在 MENU_CONF 属性下
					MENU_CONF: {
						//配置上传图片
						uploadImage: {
							customUpload: this.uploadImg,
						},
						//配置上传视频
						uploadVideo: {
							customUpload: this.uploadVideo
						}
					},
				},
				mode: 'default', // or 'simple'
				loading: true,

				applicableTargetsOptions: []
			};
		},
		methods: {
			open(type, cateInfo, info) {
				//使用富文本的清空方法clear，来清空富文本数据。
				// proxy.$refs['itemRef'].clear();
				this.loading = false
				this.activeName = '1'
				this.type = type
				this.dialogVisible = true;
				this.getApplicableTargetsOptions()
				if (this.type === "add") {
					this.title = '新增 - ' + cateInfo.cateName;
					let params = {
						"headline": "", //征集标题
						"applicableTargets": "", //适用行业：方案适用的行业、机构或领域。
						"target": "", //目标用户：方案适用的用户群体。
						"settleMatter": "", //需求描述
						"expectedEffect": "", //预期效果：预期能够达到的效果。征集要求
						"collectionTimeStart": "", //投稿时间 起
						"collectionTimeEnd": "", //投稿时间 止
						timeArr:[],
						"cover": "", //封面图
						"contactPhone": "", //联系电话
						"contactRen": "", //联系人
						"keywordes": "", //关键词
						"accessoryDtos": [ //附件
							// {
							//     "correlationId": "", //关联id
							//     "accessoryName": "", //名称
							//     "accessoryUrl": "", //url
							// }
						]
					}
					this.form = params
					this.form.schemeType = cateInfo.cateId
					this.fileAll = []
					this.imgUrl = ''
				} else if (this.type === "edit") {
					this.title = "编辑课题组";
					this.fileAll = []

					this.form.headline = info.headline
					this.form.accessoryDtos = []
					this.form.applicableTargets = info.applicableTargets
					this.form.target = info.target
					this.form.settleMatter = info.settleMatter
					this.form.expectedEffect = info.expectedEffect
					this.form.collectionTimeStart = info.collectionTimeStart
					this.form.collectionTimeEnd = info.collectionTimeEnd
					this.form.cover = info.cover
					this.form.contactPhone = info.contactPhone
					this.form.contactRen = info.contactRen
					this.form.keywordes = info.keywordes
					this.form.timeArr = [info.collectionTimeStart,info.collectionTimeEnd]
					// console.log('this.form.timeArr',this.form.timeArr)
					this.form.id = info.id
					this.imgUrl = info.cover

					if (this.form.zxLink) {
						this.checked = true
					}
					this.getDetail(info.id)
				}

			},
			// 适用行业
			getApplicableTargetsOptions() {
				getKey('applicable_industry').then(res => {
					if (res.data.code === 200) {
						this.applicableTargetsOptions = res.data.result.items
					}
				})
			},
			// 选择来源
			changeLink(val) {
				// if(){}
			},
			handleClose() {
				// this.$emit('getNewList')
				this.$refs.form.resetFields();
				const editor = this.editor
				if (editor == null) return
				editor.destroy() // 组件销毁时，及时销毁编辑器

			},
			// 父级
			selectValue() {
				this.$refs.cascader.dropDownVisible = false;
			},
			// 创建
			submitForm(val) {
				this.$refs.form.validate((valid) => {
					if (valid) {
						const loading = this.$loading({
							lock: true,
							text: 'Loading',
							spinner: 'el-icon-loading',
							background: 'rgba(0, 0, 0, 0.7)'
						});
						if (this.type === 'add') {
							this.form.checkafcd = val
							this.form.collectionTimeStart = this.form.timeArr[0]
							this.form.collectionTimeEnd = this.form.timeArr[1]
							planCollectAdd(this.form).then((res) => {

								loading.close();
								if (res.data.code === 200) {
									this.$message({
										message: res.data.message,
										type: "success",
									});
									this.$emit('getNewList')
									this.dialogVisible = false

								} else {
									this.$message.error(res.data.message);
								}
							});
						} else if (this.type === 'edit') {
							// if (this.form.verifyStatus === '2' || this.form.verifyStatus === '5') {
							// 	this.form.verifyStatus = '0'
							// }
							// if (this.checked === false) {
							// 	this.form.ntSource = ''
							// 	this.form.ntLink = ''
							// }
							this.form.checkafcd = val
							this.form.collectionTimeStart = this.form.timeArr[0]
							this.form.collectionTimeEnd = this.form.timeArr[1]
							planCollectAdd(this.form).then((res) => {

								loading.close();
								if (res.data.code === 200) {
									this.$message({
										message: res.data.message,
										type: "success",
									});
									this.$emit('getNewList')
									this.dialogVisible = false

								} else {
									this.$message.error(res.data.message);
								}
							});
						}

					} else {
						return false;
					}
				});
			},
			// 获取详情
			getDetail(id) {
				planCollectListDetail(id).then(res => {
					if (res.data.code === 200) {
						// this.form = res.data.result
						var list = res.data.result.accessoryDtos
						if (list.length !== 0) {
							list.forEach(item => {
								this.fileAll.push({
									name: item.accessoryName,
									filePath: item.accessoryUrl,
								});
							})
							list.forEach(item => {
								this.form.accessoryDtos.push({
									accessoryName: item.accessoryName,
									accessoryUrl: item.accessoryUrl,
								});
							})
						}
						this.loading = false
					}
				})
			},
			// 限制上传的类型
			beforeAvatarUpload(file) {
				const isLt10M = file.size / 1024 / 1024 < 10;
				if (!isLt10M) {
					this.$message.error("上传图片大小不能超过 10M!");
					return false;
				}
				var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
				const extension = testmsg === "jpg" || testmsg === "JPG";
				const extension2 = testmsg === "png" || testmsg === "PNG";
				if (!extension && !extension2) {
					this.$message({
						message: "上传图片只能是 jpg, png格式!",
						type: "error",
					});
					return false;
				}
			},
			// 上传文件成功
			handleAvatarSuccess(response, file) {
				this.imgUrl = URL.createObjectURL(file.raw);
				this.form.cover = response.message;
				this.$refs.headimgUpload1.clearValidate(); // 关闭校验
			},
			// 上传文件失败
			handleError(err) {
				let errInfo = JSON.parse(err["message"]);
				this.$message.error(`文件上传失败，原因:${errInfo.message}`);
			},
			//附件上传方法结束
			onEditorChange({
				editor,
				html,
				text
			}) {
				this.form.content = html;
			},
			// 上传文件成功
			handleAvatarSuccess6(response, file) {
				let params = {
					accessoryName: file.name,
					accessoryUrl: file.response.message,
				}
				this.form.accessoryDtos.push(params);
			},
			// 上传文件失败
			handleError6(err) {
				let errInfo = JSON.parse(err["message"]);
				this.$message.error(`文件上传失败，原因：${errInfo.message}`);
			},
			//删除上传的文件
			handleRemove6(response, file, fileList) {
				var dataList = this.form.fileDtos;
				for (var i = 0; i < dataList.length; i++) {
					if (dataList[i].name.indexOf(response.name) > -1) {
						var index = i;
						dataList.splice(index, 1); //存在即删除
					}
				}
				this.form.accessoryDtos = dataList
			},

			// 富文本
			onCreated(editor) {
				this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
			},
			// 富文本-上传图片
			uploadImg(file, insertFn) {
				let imgData = new FormData();
				imgData.append('file', file);
				//调接口，上传图片
				getUploadImg(imgData).then(response => {
					if (response.data.code == 200) {
						insertFn(response.data.message);
					} else {
						this.$message.error(response.data.message);
					}
				})
			},
			// 富文本-上传视频
			uploadVideo(file, insertFn) {
				let imgData = new FormData();
				imgData.append('file', file);
				//调接口，上传图片
				getUploadImg(imgData).then(response => {
					if (response.data.code == 200) {
						insertFn(response.data.message);
					} else {
						this.$message.error(response.data.message);
					}
				})
			}
		},
		// 生命周期-离开当前页面路由
		beforeDestroy() {
			const editor = this.editor
			if (editor == null) return
			editor.destroy() // 组件销毁时，及时销毁编辑器
		}
	};
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="less" scoped>
	::v-deep .ql-editor {
		min-height: 200px;
	}

	.el-input {
		width: 420px;
	}

	.el-cascader {
		width: 420px;
	}

	.el-textarea {
		width: 420px;
	}

	.el-select {
		width: 420px;
	}

	/deep/.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 120px;
		height: 120px;
		line-height: 120px;
		text-align: center;
	}

	.avatar {
		width: 120px;
		height: 120px;
		display: block;
		object-fit: contain;
	}

	.newDesc {
		position: relative;

		.el-checkbox {
			position: absolute;
			top: 14.5%;
			left: 11%;
		}
	}

	.ql-toolbar {
		position: fixed;
	}
</style>